/**
 * 队列
 */
export default class Queue<T> {

    capacity: number

    items: T[] = []

    constructor(capacity?: number) {
        this.capacity = capacity || 0
    }

    push = (data: T): boolean => {
        if (data === null) {
            return false
        }
        // 如果传递了capacity参数就设置了队列的容量
        if (this.capacity > 0) {
            if (this.items.length === this.capacity) {
                this.remove()
            }
        }
        this.items.push(data)
        return true
    }

    /**
     * 查看首位元素
     * @returns { T } 元素
     */
    first = (): T | undefined => {
        if (this.isNotEmpty()) {
            return this.items[0]
        }
        return undefined
    }

    /**
     * 查看末位元素
     * @returns { T } 元素
     */
    last = (): T | undefined => {
        if (this.isNotEmpty()) {
            return this.items[this.size() - 1]
        }
        return undefined
    }

    /**
     * 取出首位元素
     * @returns { T } 元素
     */
    peek = (): T | undefined => {
        return this.items.shift()
    }

    /**
     * 移除末位元素, 并返回
     * @returns { T } 元素
     */
    remove = (): T | undefined => {
        return this.items.pop()
    }

    /**
     * 获取队列大小
     * @returns { Number } 大小
     */
    size = (): number => {
        return this.items.length
    }

    clear = (): void => {
        delete this.items
        this.items = []
    }

    isNotEmpty = (): boolean => {
        return this.size() > 0
    }

    isEmpty = (): boolean => {
        return this.items.length === 0
    }
}
